package com.online.questionnaire.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.online.questionnaire.common.ErrorCode;
import com.online.questionnaire.common.R;
import com.online.questionnaire.common.ResultUtils;
import com.online.questionnaire.exception.ThrowUtils;
import com.online.questionnaire.model.Answer;
import com.online.questionnaire.model.SurveySubmit;
import com.online.questionnaire.model.Surveys;
import com.online.questionnaire.model.User;
import com.online.questionnaire.model.dto.AnswerSheet;
import com.online.questionnaire.model.dto.QuestionsDTO;
import com.online.questionnaire.model.dto.SubmitSurveyDTO;
import com.online.questionnaire.model.dto.SurveysDTO;
import com.online.questionnaire.service.SurveySubmitService;
import com.online.questionnaire.service.SurveysService;
import com.online.questionnaire.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.online.questionnaire.constant.UserConstant.ADMIN_ROLE;

/**
 * 答案相关 api
 */
@RestController
@RequestMapping("/answer")
@Slf4j
@Tag(name = "答卷相关接口")
public class AnswerController {

    @Resource
    private UserService userService;
    @Resource
    private SurveySubmitService surveySubmitService;
    @Resource
    private SurveysService surveysService;


    /**
     * 提交答案
     */
    @PostMapping("/submit")
    public R<Boolean> submitAnswer(@RequestBody SubmitSurveyDTO submitSurveyDTO, HttpServletRequest request) {
        if (submitSurveyDTO == null){
            ThrowUtils.paramsError("参数为空！");
        }
        if (submitSurveyDTO.getAnswerList() == null || submitSurveyDTO.getAnswerList().isEmpty()){
            ThrowUtils.paramsError("提交的答案为空！");
        }
        //遍历答案 如果value全部为空 返回
        boolean isAllEmpty = true;
        for (Answer answer : submitSurveyDTO.getAnswerList()) {
            if (answer.getValue() != null && !answer.getValue().isEmpty()){
                isAllEmpty = false;
                break;
            }
        }
        if (isAllEmpty){
            ThrowUtils.paramsError("提交的答案为空！");
        }
        boolean b = surveySubmitService.submitAnswer(submitSurveyDTO, request);
        if (!b){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"提交失败！");
        }else{
            return ResultUtils.success(b);
        }
    }

    /**
     * 获取单张答卷
     * id: 提交id
     */
    @GetMapping("/answer-sheet/{id}")
    public R<SurveysDTO> getAnswerSheet(@PathVariable Long id, HttpServletRequest request){
        if (id == null){
            ThrowUtils.paramsError("参数错误");
        }
        //检查登录
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        //检查问卷是否属于用户  或者用户为管理员
        SurveySubmit surveySubmit = surveySubmitService.getById(id);
        if (surveySubmit == null){
            ThrowUtils.paramsError("提交记录不存在！");
        }
        Surveys surveys = surveysService.getById(surveySubmit.getSurveyId());
        if (surveys == null){
            ThrowUtils.paramsError("问卷不存在！");
        }
        if (!surveys.getCreateuserid().equals(loginUser.getId())
                && !ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        AnswerSheet answerSheet = surveySubmitService.getAnswerSheet(id);
        SurveysDTO surveysDTO = surveysService.getDTOById(surveys.getId());

        //answerSheet中的将value设置到surveysDTO
        for (QuestionsDTO questionsDTO : surveysDTO.getQuestions()){
            for (Answer answer : answerSheet.getList()){
                if (answer.getQuestionId().equals(questionsDTO.getId())){
                    questionsDTO.setValue(answer.getValue());
                }
            }
        }

        return ResultUtils.success(surveysDTO);
    }


    /**
     * 获取单张试卷下的所有提交记录
     * id : 试卷id  surveyId
     */
    @GetMapping("/list/{id}")
    public R<List<SurveySubmit>> getSurveySubmitList(@PathVariable Long id, HttpServletRequest request){
        if (id == null){
            ThrowUtils.paramsError("参数错误");
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        //检查问卷是否属于自己
        Surveys surveys = surveysService.getById(id);
        if (surveys == null){
            ThrowUtils.paramsError("问卷不存在！");
        }
        if (!surveys.getCreateuserid().equals(loginUser.getId())
                && !ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        LambdaQueryWrapper<SurveySubmit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SurveySubmit::getSurveyId,id);
        //按照时间倒序
        queryWrapper.orderByDesc(SurveySubmit::getCreateTime);
        List<SurveySubmit> list = surveySubmitService.list(queryWrapper);
        //查询用户名
        for (SurveySubmit surveySubmit : list) {
            User user = userService.getById(surveySubmit.getUserId());
            if (user != null){
                surveySubmit.setUserName(user.getUserName());
            }
        }

        return ResultUtils.success(list);
    }

}
